package com.schedule.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.schedule.mapper.RoleMapper;
import com.schedule.pojo.*;
import com.schedule.service.IMenuRoleService;
import com.schedule.service.IMenuService;
import com.schedule.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/")
public class PermissionController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IMenuRoleService menuRoleService;
    @Autowired
    RoleMapper roleMapper;

    @ApiOperation(value = "获取所有角色")
    @GetMapping("/authority/menu/getAllRole")
    public List<Role> getAllRoles(){
        return roleService.list();
    }



    @ApiOperation(value = "添加角色")
    @PostMapping("/authority/menu/addRole")
    public RespBean addRole(@RequestBody Role role){
        //spring security权限都是以“ROLE_”开头的，如果不加上则不能被spring security掌控
        if(!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if(roleService.save(role)){
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败！");

    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{rid}")
    public RespBean deleteRole(@PathVariable Integer rid){
        if(roleService.removeById(rid)){
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }

    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/authority/menu/menus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }

    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/authority/menu/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        //条件构造器
        //list返回的是MenuRole对象，我们需要的是Mid，因此list之后要用stream流转换为菜单id
        return menuRoleService.list(new QueryWrapper<MenuRole>()
                .eq("rid",rid)).stream()
                .map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation(value="更新角色菜单")
    @PostMapping("/authority/menu/updateMenuRole")
    public RespBean updateMenuRole(@RequestBody UpdateMenuRoleParam updateMenuRoleParam){
        Integer rid=updateMenuRoleParam.getRid();
        Integer []mids=updateMenuRoleParam.getMids();
//        System.out.println("rid is "+rid);
//        System.out.println(mids);

        return  menuRoleService.updateMenuRole(rid,mids);
//        return RespBean.success("修改成功");
    }

}
